function aptReleaseInit() {
    var userHasRights = false;
    emosWS.addEventListener("UserRight", function(msg) {
        // Check if users have right to release devices: 
        if (AptCheckUserRight("Release")) {
            userHasRights = true;
        } else {
            userHasRights = false;
        }
        userRightsChanged(userHasRights);
    });

    var advisedId = emosWS.getNewElementId();
    var tableSelector = "apt_ReleaseTableContainer";
    var appName = sessionStorage.getItem("apt_appName");
    var robotData;
    var languageTexts = {
        "T02_ReleaseWeekendMode": {
            id: "apt_ReleaseWeekendHeader",
            text: "Release Weekend Mode"
        },
        "T02_ReleaseBGsHeader": {
            id: "apt_ReleaseBGsHeader",
            text: "BGs"
        }
    };

    $.ajax({
        url: '../../../apps/' + appName + '/global/releaseWeekend.JSON',
        type: 'post',
        dataType: 'json',
        async: true,
        cache: false,
        success: function(data) {
            createDom(data);
            robotData = data;
        },
        error: function(jqXHR, textStatus, errorThrown) {
            AptWriteLog("[APT Error] Could not read " + '../../../apps/' + appName + '/global/releaseWeekend.JSON' + ". Error: " + errorThrown + "", "error");
        }
    });

    function createDom(data) {
        var robots = Object.keys(data);
        var robotPositions = {};

        var min = [];
        var max = [];

        robots.forEach(function(robName) {
            var options = data[robName]; 
            if (!(options.hide === 1)) {
                var positionx = parseInt(options.X);
                var positiony = parseInt(options.Y);
            
                robotPositions[robName] = {
                    x: positionx,
                    y: positiony
                };

                if (min.length === 0) min = [positionx, positiony];
                if (max.length === 0) max = [positionx, positiony];

                if (positionx <= min[0]) min[0] = positionx;
                else if (positionx >= max[0]) max[0] = positionx;

                if (positiony <= min[1]) min[1] = positiony;
                else if (positiony >= max[1]) max[1] = positiony;
            }
        });

        createDynamicTable(min, max, tableSelector, "bgReleaseTable", "bgReleaseTableCell");
        var handlerObj = [];

        var opc = sessionStorage.getItem("apt_PLC.OpcTopic");
        for (var rob in data) {
            var options = data[rob];
            if (!(options.hide === 1)) {
                var x = robotPositions[rob].x;
                var y = robotPositions[rob].y;

                var html = "<div class='robReleaseWindow'>";
                html += "<table><td>" + rob + "</td>";

                var robnr = sessionStorage.getItem("apt_" + rob + ".RobNr");

                var id = getElementGlobalID();
                var overlayId = getElementGlobalID();
                var innerId = getElementGlobalID();
                html += "<td><div id='" + id + "' class='emosbutton releaseButton releaseBG '><div id = '" + overlayId + "' class='innerImageDiv'><div id = '" + innerId + "' class='innerImageDiv'></div></div></div></td>";

                var controlWeekTag = sessionStorage.getItem("apt_PLC.Tags.BG" + robnr + ".Out.Week");
                var Auto = sessionStorage.getItem("apt_PLC.Tags.BG" + robnr + ".Out.Auto");
				releaseAuto = opc + Auto;

                handlerObj.push({
                    tag: opc + controlWeekTag,
                    id: overlayId,
                    function: function(tag, id) { handleRelease(tag, id); }
                });
                handlerObj.push({
                    tag: opc + controlWeekTag,
                    id: id,
                    function: function(tag, id) { handleToggleClick(tag, id); }
                });

                html += "</table></div>";
                placeHtmlInTable(html, x, y, tableSelector);
            }
			weekendCheckAuto(releaseAuto, id);
        }

        // Execute all functions for all buttons
        handlerObj.forEach(function(obj) {
            obj.function(obj.tag, obj.id);
        });

    }

    function handleRelease(tag, id) {
        emosWS.advise(tag, function(msg) {
            if (parseInt(msg.value) === 0) {
                $('#' + id).addClass("unreleased");
            } else {
                $('#' + id).removeClass("unreleased");
            }
        }).setId(advisedId);
    }

	/*   function handleToggleClick(tag, id) {
        $('#' + id).click(function() {
         emosWS.poke(tag, +!GetTagValueAsBoolean(tag));
        });
    }*/
	
    function handleToggleClick(tag, id) {
        emosWS.advise(tag, function(msg) {
            if (parseInt(msg.value) === 0) {
				$('#' + id).click(function() {
				emosWS.poke(tag, 2);
				});
            } else {
				$('#' + id).click(function() {
				emosWS.poke(tag, 0);
				});
            }
        }).setId(advisedId);
	}
	

    function releaseAllBGs(state) {
        var opc = sessionStorage.getItem("apt_PLC.OpcTopic");
        for (var rob in robotData) {
            if (!robotData[rob].hide | !state) {
                var robnr = sessionStorage.getItem("apt_" + rob + ".RobNr");
                var tag = sessionStorage.getItem("apt_PLC.Tags.BG" + robnr + ".Out.Week");
				var AutoRelease = sessionStorage.getItem("apt_PLC.Tags.BG" + robnr + ".Out.Auto");
				var value = 0;
				emosWS.advise(opc + AutoRelease, function (msg) {
					if (msg.value == 1) {
						if (state) value = 2;
						emosWS.poke(opc + tag, value);
					}
				}).setId(advisedId);
            }
        }
    }
	
	
    function UnchekedAllBGs(state) {
        var opc = sessionStorage.getItem("apt_PLC.OpcTopic");
        for (var rob in robotData) {
            if (!robotData[rob].hide | !state) {
                var robnr = sessionStorage.getItem("apt_" + rob + ".RobNr");
                var tag = sessionStorage.getItem("apt_PLC.Tags.BG" + robnr + ".Out.Week");
				var value = 0;
				if (state) value = 2;
				emosWS.poke(opc + tag, value);
            }
        }
    }

    // function userRightsChanged() {
    //     if (userHasRights) {
    //         $('.emosbutton').removeClass("disabled");
    //     } else {
    //         $('.emosbutton').addClass("disabled");
    //     }
    // }

    function weekendCheckAuto(releaseAuto, id) {
        emosWS.advise(releaseAuto, function(msg) {
            if (((msg.value) == 1)  && (userHasRights)) {
                $('#' + id).removeClass("disabled");
            } else {
                $('#' + id).addClass("disabled");
            }
        }).setId(advisedId);
    }

    function eventHandler() {
        $('#apt_ReleaseContainer').on("remove", function() {
            emosWS.unadvise(advisedId);
        });

        $('#racBGOnButton').click(function() {
            releaseAllBGs(true);
        });

        $('#racBGOffButton').click(function() {
            UnchekedAllBGs(false);
        });

        // $('body').click(function() {
        //     if (!userHasRights) {
        //         if ($('#login').length === 0) $('#login', parent.document).trigger('click');
        //         else $('#login').trigger('click');
        //     }
        // });
    }

    languageHandler(languageTexts);
    eventHandler();
}


function initReleaseWindow() {
    emosWS.connect({ onopen: aptReleaseInit() });
}